<template>
  <div>
    <div>
      <BasicTable @register="registerTable" @row-click="handleTestDataChildRowClick">
        <!-- 表格标题 -->
        <template #tableTitle>
          <Icon :icon="getTitle.icon" class="m-1 pr-1" />
          <span> {{ getTitle.value }} </span> 
          
          <Popconfirm :title="t('确认生效选中记录吗？')" @confirm="btnvalid()">
            <a-button
              danger
              type="default"
              v-if="selectedRowKeysRef.length > 0"
              v-auth="'mf:dh:mfCarplanDhH:edit'"
              class="ml-2 mr-2"
            >
              <Icon icon="i-ant-design:check-outlined" color="error" /> {{ t('准备就绪') }} ({{
                selectedRowKeysRef.length
              }})
            </a-button>
          </Popconfirm>

          <Popconfirm :title="t('确认修改为推送状态吗？')" @confirm="btnSdPush()">
            <a-button
              ghost
              type="warning"
              v-if="selectedRowKeysRef.length > 0"
              v-auth="'mf:dh:mfCarplanDhH:sdpush'"
              class="ml-2 mr-2"
            >
              <Icon icon="i-simple-line-icons:user" /> {{ t('手动推送') }} ({{
                selectedRowKeysRef.length
              }})
            </a-button>
          </Popconfirm>

          <a-button v-if="selectedRowKeysRef.length > 0" class="ml-2 mr-2" @click="addBDetailsBtn()" v-auth="'mf:dh:mfCarplanDhH:edit'">
            <Icon icon="fluent:add-12-filled" /> {{ t('批量新增详情') }}({{
              selectedRowKeysRef.length
            }})
          </a-button>


        </template>
        <!-- 表格右上角自定义按钮（新增...） -->
        <template #toolbar>
          <div>
            <a-button class="ml-2 mr-2" ghost type="success" @click="btnOver()" v-auth="'mf:dh:mfCarplanDhH:over'">
            <Icon icon="i-ant-design:check-outlined" /> {{ t('完成称重') }}
          </a-button>
            <a-button class="mr-2" type="default" @click="handleForm({})" v-auth="'mf:dh:mfCarplanDhH:edit'">
              <Icon icon="i-fluent:add-12-filled" /> {{ t('新增') }}
            </a-button>
            <a-button class="mr-2" type="primary" @click="btnImport()" v-auth="'mf:dh:mfCarplanDhH:edit'">
              <Icon icon="ant-design:upload-outlined" /> {{ t('导入') }}
            </a-button>
          </div>
        </template>
        <template #detail="{ record }">
          <div>
            <a :style="currentDjNo === record.djNo ? { color: 'red', fontWeight: 'bold', fontSize : '20px' } : {}" @click="setCurrentDjNo(record.djNo)">{{ currentDjNo === record.djNo ? t('当前车次') : t('加载车次') }}</a>
          </div>
        </template>
      </BasicTable>
      <InputForm @register="registerDrawer" @success="handleSuccess" />
      <InputForm2 @register="registerDrawer2" @success="handleSuccess2" />


      <FormImport @register="registerImportModal" @success="handleSuccess" />
    </div>
    <!-- 子表 -->
    <div>
      <BasicTable @register="registerTable2">
        <!-- 表格标题 -->
        <template #tableTitle>
          <Icon :icon="getTitle2.icon" class="m-1 pr-1" />
          <span> {{ getTitle2.value }} </span>
          <span v-if="djNo" style="font-size: 22px;font-weight: bold;"> <span style="color: red;margin-left: 10px;font-size: 18px;font-weight: bold;">当前车次: </span> 【{{ djNo }}】 </span>
          
        </template>

        <template #toolbar>
        <a-button v-if="djNo && zbData.cstatus!='3'"  @click="addDetailsBtn()" v-auth="'mf:dh:mfCarplanDhH:edit'">
          <Icon icon="fluent:add-12-filled" /> {{ t('新增详情') }}
        </a-button>
      </template>
        
      </BasicTable>
    </div>

    <!-- width="60%" -->
    <BasicModal
      v-bind="$attrs"
      :showFooter="true"
      :okAuth="'mf:dh:mfCarplanDhH:edit'"
      @register="registerModal"
      @ok="handleOverSubmit"
    >
      <template #title>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> 修改原因：  </span> {{ overData.djNo }}
      </template>
      <BasicForm @register="registerForm" />
    </BasicModal>



    <BasicModal
      v-bind="$attrs"
      :showFooter="true"
      :okAuth="'mf:dh:mfCarplanDhH:edit'"
      @register="registerModal2"
      @ok="handleSubmit2"
      width="80%"
    >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> 添加详情</span> 
      【<DictLabel v-if="xqcarType" dictType="mf_carplan_type" :dictValue="xqcarType" defaultValue="0"/>】
    </template>
      <BasicTable @register="registerTable3" @edit-change="rowChange"></BasicTable>
      <!-- @edit-change="rowChange" -->
    </BasicModal>


    <ListSelect
      ref="listSelectRef"
      selectType="podetailsSelect"
      :checkbox="true"
      @select="handleSelect"
      :selectList="selectListRef"
      :queryParams="queryParams"
      v-show="false"
    />
    
  </div>
</template>

<script lang="ts">
  export default defineComponent({
    name: 'ViewsWmsWeighbridgeDhList',
  });
</script>
<script lang="ts" setup>
  import { Popconfirm } from 'ant-design-vue';
  import { defineComponent, watch, ref, onMounted, unref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import {
    mfCarplanDhHListData, mfCarplanDhCListData, mfCarplanDhHinvalid,
    updatePushStatusByHand, mfCarplanDhHDelete,  mfCarplanDhHupdateCstatus,
    mfCarplanDhCDelete, updateCzStatusByHand, mfCarplanDhCsaveChild, mfCarplanDhHformEdit
  } from '/@/api/wms/weighbridge/dh';
  import { useDrawer } from '/@/components/Drawer';
  import { FormProps,BasicForm, FormSchema, useForm } from '/@/components/Form';
  import InputForm from './form.vue';
  import InputForm2 from './form2.vue';
  import FormImport from './formImport.vue';
  import { useModal } from '/@/components/Modal';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { ListSelect } from '/@/components/ListSelect';
  import { DictLabel } from '/@/components/Dict';
 

  const emit = defineEmits(['success']);

  const { t } = useI18n('test.testData');
  const { showMessage } = useMessage();
  const getTitle = {
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: router.currentRoute.value.meta.title || t('采购入库装车计划管理'),
  };
  const getTitle2 = {
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: t('单据明细列表（点击单据查询对应车次明细）'),
  };

  const currentDjNo = ref < string > ('');

  const props = defineProps({
    data: { type: Object, default: {} },
  });
  watch(
    () => props.data,
    () => { },
    { immediate: true },
  );
  let zbData = ref < string > ('');
  let djNo = ref < string > ('');
  let hid = ref < string > ('');
  let overData = ref < any > ({});
  let queryParams = ref< any >({});
  const listSelectRef = ref<any>(null);
 const selectListRef = ref<any>([]);

  let openType = ref < string > ('one');
  let xqcarType = ref < string > ('');

  

  



  const [registerModal, { openModal, closeModal,setModalProps }] = useModal();
  const [registerModal2, { openModal:openModal2, closeModal:closeModal2,setModalProps:setModalProps2 }] = useModal();

 

  //配置表单内容
  const searchForm: FormProps = {
    baseColProps: { lg: 6, md: 8 },
    labelWidth: 120,
    schemas: [
      // {
      //   label: t('工艺类型'),
      //   field: 'routeType',
      //   component: 'Select',
      //   // defaultValue: props.data.flag,
      //   // dynamicDisabled: props.data.flag == undefined || props.data.flag == '' ? false : true,
      //   componentProps: {
      //     maxlength: 200,
      //     dictType: 'bas_route_type',
      //   },
      // },

      {
        label: t('到货车次'),
        field: 'djNo',
        component: 'Input',
      },
      {
        label: t('车牌号'),
        field: 'carNo',
        component: 'Input',
      },
      {
        label: t('计划到货日期'),
        field: 'planDate',
        component: 'RangePicker',
        // component: 'DatePicker',
        componentProps: {
          // format: 'YYYY-MM-DD HH:mm',
          // valueFormat: 'YYYY-MM-DD HH:mm',
          // showTime: { format: 'HH:mm' },
        },
      },
      {
        label: t('供应商'),
        field: 'venName',
        component: 'Input',
      },
      {
        label: t('存货'),
        field: 'invName',
        component: 'Input',
      },
      {
        label: t('状态'),
        field: 'cstatus',
        component: 'Select',
        componentProps: {
          dictType: 'mf_plan_status',
          allowClear: true,
        },
      },
      {
        label: t('装车类型'),
        field: 'planType',
        component: 'Select',
        componentProps: {
          dictType: 'mf_plan_type',
          allowClear: true,
        },
      },
      {
        label: t('类型'),
        field: 'carType',
        component: 'Select',
        componentProps: {
          dictType: 'mf_carplan_type',
          allowClear: true,
        },
      },
      {
        label: t('制单人'),
        field: 'createByName',
        component: 'Input',
      },
    ],
    fieldMapToTime: [['planDate', ['planDate_gte', 'planDate_lte']]],
  };

  //配置表格表头菜单
  const tableColumns: BasicColumn[] = [
    {
      title: t(''),
      width: 100,
      dataIndex: 'djNo',
      key: 'a.dj_no',
      slot: 'detail',
    },
    {
      title: t('到货车次'),
      dataIndex: 'djNo',
      key: 'a.dj_no',
      sorter: true,
      width: 100,
      align: 'left',
    },
    {
      title: t('状态'),
      dataIndex: 'cstatus',
      key: 'a.cstatus',
      sorter: true,
      width: 80,
      dictType: 'mf_plan_status',
    },
    {
      title: t('类型'),
      dataIndex: 'carType',
      key: 'a.car_type',
      sorter: true,
      width: 80,
      dictType: 'mf_carplan_type',
    },
    {
      title: t('装车类型'),
      dataIndex: 'planType',
      key: 'a.plan_type',
      sorter: true,
      width: 100,
      dictType: 'mf_plan_type',
    },
    {
      title: t('车牌号'),
      dataIndex: 'carNo',
      key: 'a.car_no',
      sorter: true,
      width: 80,
      align: 'center',
    },
    {
      title: t('计划到货日期'),
      dataIndex: 'planDate',
      key: 'a.plan_date',
      sorter: true,
      width: 150,
      align: 'center',
    },
    {
      title: t('毛重'),
      dataIndex: 'mzWeight',
      key: 'a.mz_weight',
      sorter: true,
      width: 80,
      align: 'right',
      showSummary: true,
    },
    {
      title: t('皮重'),
      dataIndex: 'pzWeight',
      key: 'a.pz_weight',
      sorter: true,
      width: 80,
      align: 'right',
      showSummary: true,
    },
    {
      title: t('净重'),
      dataIndex: 'jzWeight',
      key: 'a.jz_weight',
      sorter: true,
      width: 80,
      align: 'right',
      showSummary: true,
    },
    {
      title: t('制单人'),
      dataIndex: 'createByName',
      key: 'a.create_by_name',
      sorter: true,
      width: 100,
      align: 'left',
    },
    {
      title: t('供应商'),
      dataIndex: 'venName',
      key: 'a.ven_name',
      sorter: true,
      width: 200,
      align: 'left',
    },
    {
      title: t('存货'),
      dataIndex: 'invName',
      key: 'a.inv_name',
      sorter: true,
      width: 120,
      align: 'left',
    },
    {
      title: t('司机'),
      dataIndex: 'cdriver',
      key: 'a.cdriver',
      sorter: true,
      width: 80,
      align: 'left',
    },
    {
      title: t('司机电话'),
      dataIndex: 'driverPhone',
      key: 'a.driver_phone',
      sorter: true,
      width: 100,
      align: 'left',
    },
    {
      title: t('运输单位'),
      dataIndex: 'carVenName',
      key: 'a.car_venName',
      sorter: true,
      width: 100,
      align: 'left',
    },
    {
      title: t('U8单号'),
      dataIndex: 'u8Code',
      key: 'a.u8_code',
      sorter: true,
      width: 100,
      align: 'left',
    },

    
    {
      title: t('毛重完成时间'),
      dataIndex: 'wcDate',
      key: 'a.wc_date',
      sorter: true,
      width: 150,
      align: 'center',
    },
    {
      title: t('皮重完成时间'),
      dataIndex: 'pzDate',
      key: 'a.pz_date',
      sorter: true,
      width: 150,
      align: 'center',
    },
    {
      title: t('备注'),
      dataIndex: 'remarks',
      key: 'a.remarks',
      sorter: true,
      width: 80,
      align: 'left',
      // slot: 'firstColumn',
    },
  ];

  const tableColumns2: BasicColumn[] = [
    {
      title: t('是否推送'),
      dataIndex: 'cstatus',
      key: 'a.cstatus',
      sorter: true,
      width: 100,
      dictType: 'sys_yes_no',
    },
    {
      title: t('U8单据号'),
      dataIndex: 'u8Code',
      key: 'a.u8_code',
      sorter: true,
      width: 150,
      // align: 'center',
    },
    {
      title: t('采购订单号'),
      dataIndex: 'poCode',
      key: 'a.po_code',
      sorter: true,
      width: 150,
      // align: 'center',
    },
    {
      title: t('供应商'),
      dataIndex: 'venName',
      key: 'a.ven_name',
      sorter: true,
      width: 150,
      // align: 'center',
    },
    {
      title: t('存货编码'),
      dataIndex: 'invCode',
      key: 'a.inv_code',
      sorter: true,
      width: 150,
      // align: 'center',
    },
    {
      title: t('存货名称'),
      dataIndex: 'invName',
      key: 'a.inv_name',
      sorter: true,
      width: 150,
      // align: 'center',
    },
    {
      title: t('规格型号'),
      dataIndex: 'invStd',
      key: 'a.inv_std',
      sorter: true,
      width: 150,
      // align: 'center',
    },
    {
      title: t('计重方式'),
      dataIndex: 'weightType',
      key: 'a.weightType',
      sorter: true,
      width: 150,
      // align: 'center',
    },
    {
      title: t('合同号'),
      dataIndex: 'contractCode',
      key: 'a.contract_code',
      sorter: true,
      width: 150,
      // align: 'center',
    },
    {
      title: t('计划到货重量'),
      dataIndex: 'planWeight',
      key: 'a.plan_weight',
      sorter: true,
      width: 150,
      align: 'right',
      showSummary: true,
    },
    {
      title: t('建议入库重量'),
      dataIndex: 'jyWeight',
      key: 'a.jy_weight',
      sorter: true,
      width: 150,
      align: 'right',
    },
    {
      title: t('确认入库重量'),
      dataIndex: 'qrWeight',
      key: 'a.qr_weight',
      sorter: true,
      width: 150,
      align: 'right',
      showSummary: true,
    },
    {
      title: t('件数'),
      dataIndex: 'iqty',
      key: 'a.iqty',
      sorter: true,
      width: 150,
      align: 'right',
    },
    {
      title: t('入库仓库'),
      dataIndex: 'rkStore',
      key: 'a.rk_store',
      sorter: true,
      width: 150,
      dictType: 'mf_rk_store',
    },
    {
      title: t('供方重量'),
      dataIndex: 'gfWeight',
      key: 'a.gf_weight',
      sorter: true,
      width: 150,
      align: 'right',
    },
    {
      title: t('海关重量'),
      dataIndex: 'hgWeight',
      key: 'a.hg_weight',
      sorter: true,
      width: 150,
      align: 'right',
    },
    {
      title: t('折算系数'),
      dataIndex: 'irate',
      key: 'a.irate',
      sorter: true,
      width: 150,
      // align: 'center',
    },
  ];

  const tableColumns3: BasicColumn[] = [
    {
      title: t('到货车次'),
      dataIndex: 'hid.djNo',
      width: 150,
    },
    {
      title: t('采购订单号'),
      dataIndex: 'poCode',
      width: 150,
    },
    {
      title: t('存货编码'),
      dataIndex: 'invCode',
      width: 150,
    },
    {
      title: t('存货名称'),
      dataIndex: 'invName',
      width: 150,
    },
    {
      title: t('规格型号'),
      dataIndex: 'invStd',
      width: 150,
    },
    {
      title: t('供应商编码'),
      dataIndex: 'venCode',
      width: 150,
    },
    {
      title: t('供应商名称'),
      dataIndex: 'venName',
      width: 150,
    },
   
    {
      title: t('合同号'),
      dataIndex: 'contractCode',
      width: 150,
    },
    {
      title: t('剩余重量'),
      dataIndex: 'qty',
      width: 150,
    },
    {
      title: t('计划重量'),
      dataIndex: 'planWeight',
      width: 200,
      editRow: true,
      editComponent: 'InputNumber',
      // editComponentProps:{
      //   onChange:(e)=>{
      //     console.log(e);
      //     e = 20
      //   }
      // },
      editRule: true,
    },
  ];

  //配置表格右边操作按钮
  const actionColumn: BasicColumn = {
    width: 120,
    align: 'left',
    actions: (record: Recordable) => [
      {
        icon: 'i-clarity:note-edit-line',
        title: t('编辑'),
        onClick: handleForm.bind(this, { id: record.id }),
        auth: 'mf:dh:mfCarplanDhH:edit',
      },
      {
        icon: 'ant-design:delete-outlined',
        color: 'error',
        title: t('删除数据'),
        popConfirm: {
          title: t('是否确认删除数据'),
          confirm: handleDelete.bind(this, { id: record.id }),
        },
        auth: 'mf:dh:mfCarplanDhH:edit',
        ifShow: () => record.cstatus != '2' && record.cstatus != '3' && record.cstatus != '4',
      },
      {
        icon: 'i-simple-line-icons:reload',
        title: t('二次称重'),
        popConfirm: {
          title: t('是否确认二次称重'),
          confirm: updateCstatus.bind(this, { id: record.id }),
        },
        auth: 'mf:dh:mfCarplanDhH:edit',
        ifShow: () => record.cstatus == '2',
      },
    ],
  };


  const actionColumn2: BasicColumn = {
    width: 120,
    align: 'left',
    actions: (record: Recordable) => [
      {
        icon: 'i-clarity:note-edit-line',
        title: t('编辑'),
        onClick: handleForm2.bind(this, { id: record.id }),
        auth: 'mf:dh:mfCarplanDhH:edit',
      },
      {
        icon: 'ant-design:delete-outlined',
        color: 'error',
        title: t('删除数据'),
        popConfirm: {
          title: t('是否确认删除数据'),
          confirm: handleDelete2.bind(this, { id: record.id }),
        },
        auth: 'mf:dh:mfCarplanDhH:edit',
        // ifShow: () => record.cstatus != '3' && record.cstatus != '4',
      },
    
    ],
  };

  const inputFormSchemas: FormSchema[] = [
    {
      label: t(''),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
        rows:5
      },
      colProps: { lg: 24, md: 24 },
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  

  async function btnOver() {
    if (getSelectRows().length == 1) {
      overData.value = getSelectRows()[0];
     await openModal(true, {});
       resetFields()
    } else {
      showMessage('请选择一条数据！！');
    }
  }


  const [registerImportModal, { openModal: importModal }] = useModal();

  function btnImport() {
    importModal(true, {});
  }
  const selectedRowKeysRef = ref<string[]>([]);
  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerDrawer2, { openDrawer:openDrawer2 }] = useDrawer();

  const [registerTable, { reload, setProps, getSelectRows }] = useTable({
    api: mfCarplanDhHListData,
    beforeFetch: (params) => {
      return params;
    },
    afterFetch: (params) => {
      console.log(params,'params=====');
      
      return params;
    },
    columns: tableColumns, //配置表格内容数组对象
    formConfig: searchForm, //配置表单内容
    showTableSetting: true, //表格右上角3个默认按钮
    useSearchForm: true, //表单是否展示
    canResize: true, //表格是否flex布局
    scroll: {
      y: 250,
    },
    // rowSelection: {
    //   type: 'radio',
    // },
    defaultRowSelection: {
      onChange: (selectedRowKeys: string[], _selectedRows: Recordable[]) => {
        selectedRowKeysRef.value = selectedRowKeys;
      },
    },
    // showSummary: true,
    // summaryFunc: handleSummary,
    showCustomSummary: true,
  });

  function handleSummary(tableData: Recordable[]) {
    const totaljzWeight = tableData.reduce((prev, next) => {
      prev += next.jzWeight ? next.jzWeight : 0;
      return prev;
    }, 0);
    const totalmzWeight= tableData.reduce((prev, next) => {
      prev += next.mzWeight ? next.mzWeight : 0;
      return prev;
    }, 0);
    const totalpzWeight = tableData.reduce((prev, next) => {
      prev += next.pzWeight ? next.pzWeight : 0;
      return prev;
    }, 0);

    return [
      {
        _row: '合计',
        jzWeight: totaljzWeight.toFixed(2),
        mzWeight: totalmzWeight.toFixed(2),
        pzWeight: totalpzWeight.toFixed(2),
      },
    ];
  }

  function handleSummary2(tableData: Recordable[]) {
    const totalplanWeight = tableData.reduce((prev, next) => {
      prev += next.planWeight ? next.planWeight : 0;
      return prev;
    }, 0);
    const totalqrWeight= tableData.reduce((prev, next) => {
      prev += next.qrWeight ? next.qrWeight : 0;
      return prev;
    }, 0);
    return [
      {
        cstatus: '合计',
        planWeight: totalplanWeight.toFixed(2),
        qrWeight: totalqrWeight.toFixed(2),
      },
    ];
  }


  

  onMounted(() => {
    if (!props.data.picno) {
      setProps({
        actionColumn: actionColumn,
      });
    }
  });

  const [registerTable3, xqtable3] = useTable({
    columns: tableColumns3, //配置表格内容数组对象
    showIndexColumn: false,
    canResize: true, //表格是否flex布局
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  const [registerTable2, { reload: reload2 }] = useTable({
    api: mfCarplanDhCListData,
    beforeFetch: (params) => {
      return params;
    },
    columns: tableColumns2, //配置表格内容数组对象
    actionColumn: actionColumn2, //配置表格右边操作按钮
    // formConfig: searchForm, //配置表单内容
    // showTableSetting: true, //表格右上角3个默认按钮
    // useSearchForm: true, //表单是否展示
    showIndexColumn: false,
    canResize: true, //表格是否flex布局
    maxHeight: 400,
    immediate: false, //懒加载
    // showSummary: true,
    // summaryFunc: handleSummary2,
    showCustomSummary: true,
  });

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  function handleForm2(record: Recordable) {
    openDrawer2(true, record);
  }


  async function rowChange({ column, value, record }) {
    // if (column.dataIndex == 'planWeight') {
    //   console.log(value,'value====');
    //   record.planWeight = 666
    //   // value = 50
    //   // if(zbData.value.carType == 1){
    //   //   if (value > 0) {
    //   //     value = -value;
    //   //   }
    //   // }else{
    //   //   if (value < 0) {
    //   //     value = -value;
    //   //   }
    //   // }
    // }

    if (column.dataIndex === 'planWeight' ) {
      const { editValueRefs: { planWeight } } = record;
      // unref(planWeight).value =  666;

      if(xqcarType.value == 1){
        if (value > 0) {
          planWeight.value = -value;
        }
      }else{
        if (value < 0) {
          planWeight.value = -value;
        }
      }

    }
  }
  

  async function btnvalid() {
    if (getSelectRows().length) {
      var selIds = ref('');
      getSelectRows().forEach((item) => {
        selIds.value += item.id + ',';
      });
      const res = await mfCarplanDhHinvalid({ id: selIds.value });
      selectedRowKeysRef.value = [];
      showMessage(res.message);
      handleSuccess();
    } else {
      showMessage('请先选择车次！！');
    }
  }

  async function btnSdPush() {
    if (getSelectRows().length) {
      var selIds = ref('');
      getSelectRows().forEach((item) => {
        selIds.value += item.id + ',';
      });
      const res = await updatePushStatusByHand({ id: selIds.value });
      selectedRowKeysRef.value = [];
      showMessage(res.message);
      handleSuccess();
    } else {
      showMessage('请先选择车次！！');
    }
  }

  async function handleSelect(selectData) {
    console.log(selectData,'data====');
    xqcarType.value = openType.value =='one'?zbData.value.carType:getSelectRows()[0].carType

    const res = await mfCarplanDhHformEdit({
      ids:hid.value,
      carType:xqcarType.value,
      selectData: window.encodeURI(JSON.stringify(selectData)) 
    })
    await openModal2(true, {});
    await xqtable3.setTableData([])
    // await xqtable3.setTableData(res.mfCarplanDhCList)
    res.mfCarplanDhCList.forEach((item) => {
      xqtable3.insertTableDataRecord({
        editable: true,
        ...item,
        id:'',
      });
    });



    // selectData.forEach((item) => {
    //   xqtable3.insertTableDataRecord({
    //     editable: true,
    //     // ...item,
    //     id:'',
    //     'hid':{
    //       id:hid.value,
    //     },
    //     cid:item.id,
    //     poCode:item.cpoid,
    //     invCode:item.cinvCode,
    //     invName:item.cinvName,
    //     invStd:item.cinvStd,
    //     venCode:item.cvenCode,
    //     venName:item.cvenName,
    //     contractCode:item.contractCode,
    //     rkStore:item.rkStore,
    //     qty:item.qty,
    //     cinvDefine1:item.cinvDefine1,
        
    //   });
    // });
  }

  async function getChildList() {
    let childListValid = true;
    let childList: Recordable[] = [];
    for (const record of xqtable3.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        childListValid = false;
      }
      childList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    
    if (!childListValid) {
      throw { errorFields: [{ name: ['childList'] }] };
    }
    return childList;
  }

  async function handleSubmit2() {
    try {
      let data = {}
      setModalProps2({ confirmLoading: true });
      data.mfCarplanDhCList = await getChildList();


      const res = await mfCarplanDhCsaveChild(data);
      showMessage(res.message);
      handleSuccess2();
      closeModal2();
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setModalProps2({ confirmLoading: false });
    }
  }



  // 鼠标行点击事件，获取上表数据
  function handleTestDataChildRowClick(record: Recordable) {
    currentDjNo.value = record.djNo;
    djNo.value = record.djNo;
    hid.value = record.id;
    zbData.value = record;
    // record.onEdit?.(true, false);
    reload2({
      searchInfo: { 'hid.id': record.id },
    });
  }

  

  async function handleOverSubmit(record: Recordable) {
    try {
      const data = await validate();
      data.id = overData.value.id
      data.djNo = overData.value.djNo
      data.cstatus = '2'
      setModalProps({ confirmLoading: true });
      const res = await updateCzStatusByHand(data);
      selectedRowKeysRef.value = [];
      showMessage(res.message);
      handleSuccess();
      closeModal();
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  async function handleDelete(record: Recordable) {
    const res = await mfCarplanDhHDelete(record);
    showMessage(res.message);
    handleSuccess();
  }

  async function handleDelete2(record: Recordable) {
    const res = await mfCarplanDhCDelete(record);
    showMessage(res.message);
    handleSuccess2();
  }

  async function addDetailsBtn() {
    hid.value = zbData.value.id
    openType.value = 'one'

    
    selectListRef.value = []
    queryParams.value = {
      carType:zbData.value.carType
    }
    setTimeout(()=>{
     listSelectRef.value.openSelectModal();
    })
  }


  async function addBDetailsBtn() {
    openType.value = 'all'

    if (getSelectRows().length) {
      var selIds = ref('');
      let flag = true
      let carType = getSelectRows()[0].carType
      getSelectRows().forEach((item) => {
        if(item.carType != carType){
          flag = false
        }
        selIds.value += item.id + ',';
      });

      if(!flag){
        showMessage('请选择相同类型车次！！');
      }else{
        hid.value = selIds.value
        selectListRef.value = []
        queryParams.value = {
          carType:carType
        }
        setTimeout(()=>{
        listSelectRef.value.openSelectModal();
        })
      }
    } else {
      showMessage('请先选择车次！！');
    }



   
  }



  

  async function updateCstatus(record: Recordable) {
    const res = await mfCarplanDhHupdateCstatus({cstatus: 1,id:record.id});
    showMessage(res.message);
    handleSuccess();
  }

  

  function handleSuccess() {
    emit('success');
    reload();
  }

  function handleSuccess2() {
    reload2({
      searchInfo: { 'hid.id': hid.value},
    });
  }
  function setCurrentDjNo(djNo: string) {
    currentDjNo.value = djNo;
  }
</script>
